import React, { useState, useEffect } from 'react';
import { router, withRouter } from 'umi';
import { Card, Button, Collapse, Icon, Table, message } from 'antd';
import { useRequest } from '@/hooks';
import FunctionDescribe from '@/components/NewFunction/FunctionDescribe';
import { GuideByServerFlag, PageHeaderWrapper } from '@/components';
import { removeEmptyChildren } from '@/utils/tree';
import LabelValue from '@/components/LabelValue';
import { gotoWorkFlowDetail } from '@/pages/WorkFlow/utils';
import authHelper from '@/utils/auth/helper';
import { getNewFunctionDetail, getNewFunctionDetailTree, setNewFunctionRead } from '../../services';
import { filterSoftwarePlatform } from '../utils';
import { FUNCTION_TYPE, FUNCTION_GRADE, ORGANIZATIONAL_SCOPE, ADMINISTRATIVE_SCOPE } from '../constants';
import styles from '../index.less';

const { checkCode } = authHelper;

const NewFunction = ({ location }) => {
    const [isApproving, setIsApproving] = useState(false);
    const [detail, setDetail] = useState({});
    const [dataSource, setDataSource] = useState([]);
    const { userCode } = JSON.parse(localStorage.getItem('user') || '{}');

    const { query } = location;
    const { resourceCode, auditStatus } = query;

    const { run: fetchNewFunctionRead } = useRequest(params => setNewFunctionRead(params), {
        manual: true
    });

    const { run: fetchNewFunctionDetail } = useRequest(params => getNewFunctionDetail(params), {
        manual: true,
        onSuccess: ({ msg, code, data }) => {
            if (code === 10000) {
                const { auditStatus: status } = data;
                const isDisabled = status === 1 || status === 2;
                setIsApproving(isDisabled);
                fetchNewFunctionRead({ resourceCode: data.code, userCode });
                setDetail(data);
            } else {
                message.error(msg);
            }
        }
    });

    const { run: fetchNewFunctionDetailTree } = useRequest(params => getNewFunctionDetailTree(params), {
        manual: true,
        onSuccess: ({ msg, code, data }) => {
            if (code === 10000) {
                const result = removeEmptyChildren([data]);
                setDataSource(result);
            } else {
                message.error(msg);
            }
        }
    });

    useEffect(() => {
        fetchNewFunctionDetail({ resourceCode, auditStatus });
        fetchNewFunctionDetailTree({ resourceCode, auditStatus });
    }, [auditStatus, fetchNewFunctionDetail, fetchNewFunctionDetailTree, resourceCode]);

    const columns = [
        {
            title: '功能',
            dataIndex: 'nameZh',
            width: 300
        },
        {
            title: '类型',
            dataIndex: 'type',
            width: 150,
            render: value => <span>{FUNCTION_TYPE[value]}</span>
        },
        {
            title: '等级',
            dataIndex: 'functionGrade',
            width: 100,
            render: value => <span className={`functionGrade-${value}`}>{FUNCTION_GRADE[value]}</span>
        },
        {
            title: () => (
                <div className={styles.newFunctionTableHeader}>
                    <div>业务端实现情况</div>
                    <ul>
                        <li>Web端</li>
                        <li>APP端</li>
                        <li>PC端</li>
                    </ul>
                </div>
            ),
            dataIndex: 'terminalScope',
            width: 200,
            render: (value = {}) => {
                const { WEB, APP, PC } = value;
                return (
                    <div className={styles.functionIncidenceWrapper}>
                        {WEB ? <Icon type="check" /> : <Icon type="minus" />}
                        {APP ? <Icon type="check" /> : <Icon type="minus" />}
                        {PC ? <Icon type="check" /> : <Icon type="minus" />}
                    </div>
                );
            }
        }
    ];

    // 连接至流程
    const handleLinkToWorkFlow = auditCode => {
        history.push(gotoWorkFlowDetail(auditCode));
    };

    const handleLinkToDeploy = () => {
        history.push({
            pathname: '/setting/privilege/newFunctionDeploy',
            query: { resourceCode: detail.code, auditStatus }
        });
    };

    return (
        <PageHeaderWrapper>
            <GuideByServerFlag serverStorageKey="guideNewFunctionDetail">
                <Card bordered={false} className={styles.newFunctionWrapper}>
                    <header className={styles.pageHeader}>
                        <h2>新功能详情</h2>
                        {Object.keys(detail).length > 0 && !isApproving && (
                            <GuideByServerFlag.Step
                                placement="left"
                                content={
                                    <>
                                        在这里可以配置新功能权限
                                        <br />
                                        了解功能详情后，可进行配置
                                    </>
                                }
                            >
                                <Button
                                    type="primary"
                                    onClick={handleLinkToDeploy}
                                    disabled={!checkCode('system:authorization:new:edit')}
                                >
                                    配置权限
                                </Button>
                            </GuideByServerFlag.Step>
                        )}
                        {Object.keys(detail).length > 0 && isApproving && (
                            <Button type="primary" onClick={() => handleLinkToWorkFlow(detail.auditCode)}>
                                查看审批详情
                            </Button>
                        )}
                    </header>
                    <FunctionDescribe
                        title={detail.nameZh}
                        describe={detail.onlineRemarkZh}
                        releaseTime={detail.onlineTime}
                    />
                    <Collapse
                        className={styles.collapsePanel}
                        bordered={false}
                        expandIconPosition="right"
                        defaultActiveKey={['newFunctionDetail', 'newFunctionTree']}
                        expandIcon={panelProps => {
                            const { isActive } = panelProps;
                            return (
                                <div className={styles.collapseExpandIcon}>
                                    {isActive ? '收起' : '展开'}
                                    {isActive ? <Icon type="caret-up" /> : <Icon type="caret-down" />}
                                </div>
                            );
                        }}
                    >
                        <Collapse.Panel header="功能详情" key="newFunctionDetail">
                            <div className={styles.functionDescribeList}>
                                <LabelValue label="功能中文名称" value={detail.nameZh} />
                                <LabelValue label="功能英文名称" value={detail.nameEn} />
                                <LabelValue label="功能类型" value={FUNCTION_TYPE[detail.type]} />
                                <LabelValue label="从属功能" value={detail.parentNameZh} />
                                <LabelValue label="模块简介（中文）" value={detail.remarkZh} />
                                <LabelValue label="模块简介（英文）" value={detail.remarkEn} />
                                <LabelValue
                                    label="业务端实现情况"
                                    value={filterSoftwarePlatform(detail.terminalScope)}
                                />
                                <LabelValue label="初始等级" value={FUNCTION_GRADE[detail.functionGrade]} />
                                {detail?.type === 1 && (
                                    <LabelValue
                                        label="初始数据权限"
                                        value={`行政机构：${ADMINISTRATIVE_SCOPE[detail.defaultAdministrativeScope] ||
                                            ''}<br />组织机构：${ORGANIZATIONAL_SCOPE[
                                            detail.defaultOrganizationalScope
                                        ] || ''}`}
                                    />
                                )}
                            </div>
                        </Collapse.Panel>
                        {detail?.type !== 3 && (
                            <Collapse.Panel header="子功能" key="newFunctionTree">
                                <div className={styles.functionList}>
                                    <Table
                                        className={styles.functionListTable}
                                        columns={columns}
                                        pagination={false}
                                        rowKey="code"
                                        dataSource={dataSource}
                                        expandIcon={({ expanded, onExpand, record }) => {
                                            const { children } = record;
                                            if (!children) {
                                                return <span style={{ width: 14, height: 14 }} />;
                                            }
                                            return expanded ? (
                                                <Icon
                                                    type="caret-down"
                                                    style={{ marginRight: 5 }}
                                                    onClick={e => onExpand(record, e)}
                                                />
                                            ) : (
                                                <Icon
                                                    type="caret-right"
                                                    style={{ marginRight: 5 }}
                                                    onClick={e => onExpand(record, e)}
                                                />
                                            );
                                        }}
                                    />
                                </div>
                            </Collapse.Panel>
                        )}
                    </Collapse>
                </Card>
            </GuideByServerFlag>
        </PageHeaderWrapper>
    );
};

export default withRouter(NewFunction);
